
var map, plotDraw, plotEdit, shapeLayer;
var delBtn = document.getElementById('btn-delete')

function init() {
  map = new ol.Map({
    target: "map",
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([116.46, 39.92]),
      zoom: 10
    })
  });

  // 初始化标绘绘制工具，添加绘制结束事件响应
  plotDraw = new P.PlotDraw(map);
  // 监听绘制完成的时间，绘制完成后触发onDrawEnd事件
  plotDraw.on(P.Event.PlotDrawEvent.DRAW_END, onDrawEnd, false, this);

  // 初始化标绘编辑工具
  plotEdit = new P.PlotEdit(map);

  shapeLayer = new ol.layer.Vector({
    source: new ol.source.Vector()
  });

  shapeLayer.setMap(map);

  // map点击事件
  map.on('click', function (e) {
    if (plotDraw.isDrawing()) {
      return;
    }
    // 判断点击的位置有没有图形
    var feature = map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
      return feature;
    });
    if (feature) {
      plotEdit.activate(feature);
      activeDelBtn();
    } else {
      plotEdit.deactivate();
      deactiveDelBtn();
    }
  })

  delBtn.onclick = function () {
    if (shapeLayer && plotEdit && plotEdit.activePlot) {
      shapeLayer.getSource().removeFeature(plotEdit.activePlot);
      plotEdit.deactivate();
      deactiveDelBtn();
    }
  }


}



// 指定标绘类型，开始绘制。
function activate(type) {
  // 关闭编辑
  plotEdit.deactivate();
  // 激活绘制，参数类型
  plotDraw.activate(type);
};


// 绘制结束后，添加到FeatureOverlay显示。
function onDrawEnd(event) {
  var feature = event.feature
  shapeLayer.getSource().addFeature(feature);
  activeDelBtn();
}

// 删除按钮显示
function activeDelBtn() {
  delBtn.style.display = "inline-block";
}

// 删除按钮隐藏
function deactiveDelBtn() {
  delBtn.style.display = "none";
}